<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-13 10:15:48
 * @LastEditors: your name
 * @LastEditTime: 2021-05-27 15:01:41
 * @Description: file content
-->
<template>
  <el-dialog
    :visible.sync="showVisible"
    center
    :show-close="false"
    width="1200px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建服务" : "编辑服务" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="close"></span>
      </div>
    </div>

    <div class="pl30 pr30">
      <el-row :gutter="40" type="flex">
        <el-col :span="10">
          <el-form :model="formData" ref="form" label-width="120px">
            <el-form-item
              label="服务Key"
              prop="key"
              :rules="[
                {
                  required: true,
                  message: '服务Key不能为空',
                  trigger: 'change',
                },
                {
                  pattern: COMMON_CODE_64I_REG.pattern,
                  message: '请输入有效的服务Key',
                  trigger: 'change',
                },
              ]"
            >
              <template slot="label"
                >服务Key
                <el-tooltip
                  popper-class="custom-popper"
                  :content="COMMON_CODE_64I_REG.message"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-input
                :disabled="!isNew"
                v-model="formData.key"
                placeholder="请输入服务Key"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item
              label="服务名称"
              prop="name"
              :rules="[
                {
                  required: true,
                  message: '服务名称不能为空',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model="formData.name"
                placeholder="请输入服务名称"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item label="服务描述">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="请输入服务描述"
                :maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item
              label="认证方式"
              prop="authType"
              :rules="[
                {
                  required: true,
                  message: '请选择认证方式',
                  trigger: 'change',
                },
              ]"
            >
              <!-- <el-radio-group
                :disabled="!isNew"
                v-model="formData.authType"
                @change="handleAuthTypeChange"
              >
                <el-radio v-for="(label,key) in AUTH_TYPE_ENUM" :key="key" :label="key">{{ label }}</el-radio>
              </el-radio-group> -->
              <el-select
                :disabled="!isNew"
                style="width: 100%"
                v-model="formData.authType"
                @change="handleAuthTypeChange"
              >
                <el-option
                  v-for="(value, key) in AUTH_TYPE_ENUM"
                  :key="key"
                  :value="key"
                  :label="value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14" style="border-left: 1px solid #dcdfe6">
          <el-tabs v-model="activeName">
            <el-tab-pane label="本地部署" name="NATIVE">
              <el-tabs v-model="activeTab">
                <el-tab-pane
                  v-for="(item, index) in envConfigList"
                  :key="index"
                  :label="item.name"
                  :name="item.key"
                >
                  <HttpServiceEnvForm
                    :ref="`NATIVE_${item.key}_EnvForm`"
                    :authType="formData.authType"
                    :env="item.key"
                  />
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
            <el-tab-pane label="云部署" name="CLOUD">
              <div>
                <el-button size="small" @click="openCloudInstanceDialog">
                  添加
                </el-button>
              </div>
              <el-tabs
                v-model="activeTab_cloud"
                closable
                @tab-remove="removeInstance"
              >
                <el-tab-pane
                  v-for="(item, index) in instanceConfigList"
                  :key="item.env"
                  :label="item.instanceName + '（' + item.envName + '）'"
                  :name="item.env"
                >
                  <HttpServiceEnvForm
                    :ref="`CLOUD_${item.env}_EnvForm`"
                    :authType="formData.authType"
                    :env="item.env"
                    type="CLOUD"
                    :envName="item.envName"
                    :instanceName="item.instanceName"
                  />
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="tr">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>

    <DeployForm ref="DeployForm" @ok="addCloudInstance" />
  </el-dialog>
</template>

<script>
import { AUTH_TYPE_ENUM, COMMON_ENV_ENUM } from "@/utils/enum"
import { COMMON_CODE_64I_REG } from "@/utils/reg"

import HttpServiceEnvForm from "./HttpServiceEnvForm"
import DeployForm from "./DeployForm"
import {
  postHmhttpservice,
  putHmhttpservice,
} from "@/apis/paas/HmHttpServiceController.js"
import { getHmenvironmentList } from "@/apis/paas/HmEnvironmentController.js"
const defaultTab = Object.keys(COMMON_ENV_ENUM)[0]
const defaultFormData = {
  authType: Object.keys(AUTH_TYPE_ENUM)[0],
}

export default {
  name: "HttpServiceForm",
  components: {
    HttpServiceEnvForm,
    DeployForm,
  },
  data() {
    return {
      loading: false,
      COMMON_ENV_ENUM,
      AUTH_TYPE_ENUM,
      COMMON_CODE_64I_REG,
      showVisible: false,
      envConfigList: [], // 系统显示的环境
      envConfigHiddenList: [], // 隐藏的配置项
      formData: {},
      activeTab: defaultTab,
      callback: () => {},
      activeName: "NATIVE",
      activeTab_cloud: null,
      instanceConfigList: [], // 云环境的实例
    }
  },

  computed: {
    isNew() {
      return !this.formData.id
    },
  },

  methods: {
    async open(data = {}, callback) {
      this.envConfigList = await getHmenvironmentList({ hidden: 0 })
      this.showVisible = true
      this.callback = callback
      //本地部署
      const settingList = (data.settingList || []).filter(
        (i) => i.type !== "CLOUD"
      )
      //云部署
      this.instanceConfigList = (data.settingList || []).filter(
        (i) => i.type === "CLOUD"
      )
      console.log(this.instanceConfigList, "instanceConfigList")
      this.activeTab_cloud = this.instanceConfigList[0]
        ? this.instanceConfigList[0].env
        : null
      this.formData = {
        ...data,
        ...(data.id ? {} : defaultFormData),
      }
      this.activeName = "NATIVE"

      // 本地部署
      this.activeTab = defaultTab

      this.$nextTick(() => {
        this.$refs.form.clearValidate()

        // 本地部署 start
        // 获取隐藏了的配置
        settingList.forEach((item) => {
          const res = this.envConfigList.find(
            (config) => config.key === item.env
          )
          if (!res) {
            this.envConfigHiddenList.push(item)
          }
        })
        this.envConfigList.forEach((item, index) => {
          // 获取对应环境的配置项
          const config = (settingList || []).find(
            (config) => config.env === item.key
          )
          // 对应ref的form
          const form = this.$refs[`NATIVE_${item.key}_EnvForm`][0]
          form.setData(config)
        })
        // 本地部署 end

        this.instanceConfigList.forEach((item) => {
          // 对应ref的form
          const form = this.$refs[`CLOUD_${item.env}_EnvForm`][0]
          form.setData(item)
        })
      })
    },
    //认证方式切换
    handleAuthTypeChange() {
      this.activeTab = defaultTab
    },
    //云部署 添加实例弹窗
    openCloudInstanceDialog() {
      this.$refs.DeployForm.addForm(this.instanceConfigList)
    },
    //云部署 添加实例item
    addCloudInstance(item) {
      this.instanceConfigList.push(item)
      this.$nextTick(() => {
        this.activeTab_cloud = `${item.env}`
        const form = this.$refs[`CLOUD_${item.env}_EnvForm`][0]
        form.setData(item)
      })
    },
    removeInstance(targetName) {
      let tabs = this.instanceConfigList
      let activeName = this.activeTab_cloud
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (`${tab.env}` === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = `${nextTab.env}`
            }
          }
        })
      }
      this.instanceConfigList = tabs.filter(
        (tab) => `${tab.env}` !== targetName
      )
      this.$nextTick(() => {
        this.activeTab_cloud = activeName
      })
    },
    async submit() {
      try {
        await this.$refs.form.validate()
        //本地部署 校验
        const envResList = await Promise.all(
          this.envConfigList.map((item, index) => {
            const form = this.$refs[`NATIVE_${item.key}_EnvForm`][0]
            return form.getData()
          })
        )
        const settingList = []
        for (var i = 0; i < envResList.length; i++) {
          const res = envResList[i]
          if (res === false) {
            this.activeName = "NATIVE"
            this.activeTab = this.envConfigList[i].key
            return
          }
          res.serverUrl && settingList.push(res)
        }

        //云部署 校验
        const insResList = await Promise.all(
          this.instanceConfigList.map((item, index) => {
            const form = this.$refs[`CLOUD_${item.env}_EnvForm`][0]
            return form.getData()
          })
        )
        const instanceList = []
        for (var i = 0; i < insResList.length; i++) {
          const res = insResList[i]
          if (res === false) {
            this.activeName = "CLOUD"
            this.activeTab_cloud = this.instanceConfigList[i].env
            return
          }
          res.serverUrl && instanceList.push(res)
        }

        let params = {}
        let request = null

        const { id, key, name, authType, remark } = this.formData
        if (this.isNew) {
          request = postHmhttpservice
          params = { key, name, authType, remark }
        } else {
          request = putHmhttpservice
          params = { id, name, remark, authType }
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key]
        }
        params.settingList = [
          ...settingList,
          ...this.envConfigHiddenList,
          ...instanceList,
        ]
        console.log(params, "params")
        request(params)
          .then((res) => {
            this.close()
            this.callback()
          })
          .finally(() => {})
      } catch (error) {
        console.log(error)
        return false
      }
    },
    //取消
    close() {
      this.activeName = "NATIVE"
      this.showVisible = false
      this.envConfigHiddenList = []
    },
  },
}
</script>

<style lang="scss" scoped></style>
